package com.dl.dlcommon.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author DL
 * @create 2024-01-18 16:09
 */
public class EncryptionUtil {

    private static final int KEY_LENGTH = 16;

    public static final String KEY = "this is a key 666666";


    public static void main(String[] args) throws Exception {

        String xmlString = "<data>报文明细数据</data>";
        String key = "this is a key 666666"; // 替换为你的密钥

        String encryptedXml = encrypt(xmlString, key);
        System.out.println("加密后的报文：" + encryptedXml);

        String decryptedString = decryption(encryptedXml, key);
        System.out.println("解密后的字符串: " + decryptedString);
    }


    public static String encrypt(String content, String key) throws Exception {
        key = getKey(key);
        // 加密
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedData = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        String encryptedString = Base64.getEncoder().encodeToString(encryptedData);
        return encryptedString;
    }

    public static String decryption (String content, String key) throws Exception {
        key = getKey(key);
        // 解密
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"));
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(content));
        String decryptedString = new String(decryptedData, StandardCharsets.UTF_8);

        return decryptedString;
    }

    public static String getKey (String key) throws Exception {
        int keyLength = KEY_LENGTH; // 指定所需的密钥长度（16、24或32）
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        if (keyBytes.length < keyLength) {
            // 补齐密钥
            byte[] paddedKey = new byte[keyLength];
            System.arraycopy(keyBytes, 0, paddedKey, 0, keyBytes.length);
            keyBytes = paddedKey;
        } else if (keyBytes.length > keyLength) {
            // 截断密钥
            byte[] truncatedKey = new byte[keyLength];
            System.arraycopy(keyBytes, 0, truncatedKey, 0, keyLength);
            keyBytes = truncatedKey;
        }
        return new String(keyBytes, StandardCharsets.UTF_8);
    }
}
